import { TMenu } from "@/router/menu";
import router from "@/router";
import Layout from "../layout/index.vue";
import { Route404 } from "@/router/localRouters";

const modules = import.meta.glob(["../views/**/*.vue", "!**/components/**"]);

const checkRootRedirect = (path?: string, redirect?: string) =>
  path == "/" && !!redirect;

// 已注册全量路由名称
const routeNames = new Set<string>();
let redirectRoute: string | undefined = undefined;

// 向router里注册路由
function appendRouteCore(menus: TMenu[], parentName?: string) {
  menus.forEach((item) => {
    const {
      icon,
      name,
      path,
      title,
      component,
      children,
      redirect,
      hidden,
      parentRoute,

      props = false,
      isTopPage = false,
      keepAlive = false,
      disableTab = false,
      autoDestroyTab = false,
      type = "name",
    } = item;

    routeNames.add(name);

    // 当前配置是否是默认打开页面
    const isRootRedirect = checkRootRedirect(path, redirect);

    // 若无主动设置默认打开页面，设置为第一个非隐藏页面
    redirectRoute = isRootRedirect
      ? undefined
      : !redirectRoute && component && !hidden
      ? path
      : redirectRoute;

    const route = {
      name,
      path,
      redirect,
      component: isRootRedirect
        ? undefined
        : component
        ? modules[`../${component}`]
        : Layout,
      props,
      children: [],
      meta: {
        icon,
        type,
        title,
        keepAlive,
        disableTab,
        parentRoute,
        autoDestroyTab,
      },
    };

    const hasChild = children && children.length > 0;

    if (isTopPage || (hasChild && name && !parentName)) {
      router.addRoute(route);
    } else {
      router.addRoute(parentName ?? "Layout", route);
    }

    hasChild && appendRouteCore(children, name);
  });
}

// 全量移除已注册路由
const removeRoute = () => {
  routeNames.forEach(router.removeRoute);
  routeNames.clear();
};

const addCompatibleRoute = () => {
  // 全局注册一次404路由
  routeNames.add(Route404.name);
  router.addRoute("Layout", Route404);

  // 注册当前默认重定向页面
  if (redirectRoute) {
    const name = `RedirectRoute${+new Date()}`;
    routeNames.add(name);
    router.addRoute("Layout", {
      name,
      path: "/",
      redirect: redirectRoute,
    });
  }
};

// 对外提供注册方法
const appendRoute = (menus: TMenu[]) => {
  appendRouteCore(menus);

  addCompatibleRoute();
  return redirectRoute;
};

export { appendRoute, removeRoute };
